﻿using ActiproSoftware.Windows.Controls.DataGrid;
using IHateWorking.Model;
using IHateWorking.View;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using Button = System.Windows.Controls.Button;
using MenuItem = System.Windows.Controls.MenuItem;
using MessageBox = System.Windows.MessageBox;
//#JMJ Create_20241124

namespace IHateWorking.ViewModel
{
    /// <summary>
    /// 音乐清单的 ViewModel
    /// </summary>
    public class MusicListViewModel : INotifyPropertyChanged
    {
        public MusicListViewModel()
        {
            Instance = this;
            ViewLoadedCommand = new CommandBase(ViewLoaded);
            BtnCommand = new CommandBase(BtnClick);
            KeyDownCommand = new CommandBase(KeyDown);
            MouseDoubleClickCommand = new CommandBase(MouseDoubleClick_List);
        }

        #region 变量的通知机制
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
        { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); }
        #endregion 以上：变量的通知机制

        #region //////////////////////////////静态变量//////////////////////////////
        /// <summary>
        /// 静态接口
        /// </summary>
        public static MusicListViewModel Instance { get; set; }

        #endregion 以上：/////////////////////静态变量//////////////////////////////


        #region //////////////////////////////非静态变量////////////////////////////

        /// <summary>
        /// 界面加载完成 Command
        /// </summary>
        public CommandBase ViewLoadedCommand { get; set; }

        /// <summary>
        /// 按钮 Command
        /// </summary>
        public CommandBase BtnCommand { get; set; }

        /// <summary>
        /// 键盘按下 Command
        /// </summary>
        public CommandBase KeyDownCommand { get; set; }

        /// <summary>
        /// 双击 Command
        /// </summary>
        public CommandBase MouseDoubleClickCommand { get; set; }

        /// <summary>
        /// 窗体界面
        /// </summary>
        public MusicList MusicListView { get; set; }

        private SubState _vis_Vinyl = new SubState("Vis_Vinyl");
        /// <summary>
        /// 黑胶页的显示/隐藏
        /// </summary>
        public SubState Vis_Vinyl
        {
            get => _vis_Vinyl;
            set
            {
                if (_vis_Vinyl != value)
                {
                    _vis_Vinyl = value;
                    OnPropertyChanged();
                }
            }
        }

        private SubState _vis_IntrDetailView = new SubState("Vis_IntrDetailView");
        /// <summary>
        /// 详情页的显示/隐藏
        /// </summary>
        public SubState Vis_IntrDetailView
        {
            get => _vis_IntrDetailView;
            set
            {
                if (_vis_IntrDetailView != value)
                {
                    _vis_IntrDetailView = value;
                    OnPropertyChanged();
                }
            }
        }

        private bool _creator = false;
        /// <summary>
        /// 是否为创作者
        /// </summary>
        public bool Creator
        {
            get => _creator;
            set
            {
                if (_creator != value)
                {
                    _creator = value;
                    OnPropertyChanged();
                }
            }
        }

        private SubState _musicListViewState = new SubState("MusicListViewState");
        /// <summary>
        /// 窗体尺寸状态
        /// </summary>
        public SubState MusicListViewState
        {
            get => _musicListViewState;
            set
            {
                if (_musicListViewState != value)
                {
                    _musicListViewState = value;
                    OnPropertyChanged();
                }
            }
        }

        private DependencyObject _latestClickUI = new DependencyObject();
        /// <summary>
        /// 最新的鼠标按下控件
        /// </summary>
        public DependencyObject LatestClickedUI
        {
            get => _latestClickUI;
            set
            {
                if (_latestClickUI != value)
                { _latestClickUI = value; }
            }
        }

        private Music _selectedMusic;
        /// <summary>
        /// 歌曲列表中选中的音乐
        /// </summary>
        public Music SelectedMusic
        {
            get => _selectedMusic;
            set
            {
                if (_selectedMusic != value)
                {
                    _selectedMusic = value;
                    OnPropertyChanged();
                }
            }
        }

        private ObservableCollection<Music> _musicList = new ObservableCollection<Music>();
        /// <summary>
        /// 歌曲列表
        /// </summary>
        public ObservableCollection<Music> MusicList
        {
            get => _musicList;
            set
            {
                if (_musicList != value)
                {
                    _musicList = value;
                    OnPropertyChanged();
                }
            }
        }

        private int _platformID = -1;
        /// <summary>
        /// 平台 ID
        /// 0:网易云音乐
        /// 1:QQ音乐
        /// </summary>
        public int PlatformID
        {
            get => _platformID;
            set
            {
                if (_platformID != value)
                {
                    _platformID = value;

                    if (value > -1)
                    {
                        foreach (Music music in MusicList)
                        {
                            if (value < MusicListView.cB_Platform.Items.Count)
                            {
                                string key = (MusicListView.cB_Platform.Items[value] as ComboBoxItem).Content.ToString();
                                if (music.Url_Dic.ContainsKey(key))
                                { music.CurrentUrl = music.Url_Dic[key]; }
                                else
                                { music.CurrentUrl = music.Url_Dic["Local"]; }
                            }
                        }
                    }
                    OnPropertyChanged();
                }
            }
        }
        private InfoType _detail_Type = InfoType.歌曲;
        /// <summary>
        /// 详情页的信息类型
        /// </summary>
        public InfoType Detail_Type
        {
            get => _detail_Type;
            set
            {
                if (_detail_Type != value)
                { _detail_Type = value; }
            }
        }

        private string _list_Title = "小金的歌单";
        /// <summary>
        /// 歌单页的标题
        /// </summary>
        public string List_Title
        {
            get => _list_Title;
            set
            {
                if (_list_Title != value)
                {
                    _list_Title = value;
                    OnPropertyChanged();
                }
            }
        }

        private string _detail_Title;
        /// <summary>
        /// 详情页的标题
        /// </summary>
        public string Detail_Title
        {
            get => _detail_Title;
            set
            {
                if (_detail_Title != value)
                {
                    _detail_Title = value;
                    OnPropertyChanged();
                }
            }
        }

        private List<IntrLine> _detail_Intr = new List<IntrLine>();
        /// <summary>
        /// 详情页的介绍内容
        /// </summary>
        public List<IntrLine> Detail_Intr
        {
            get => _detail_Intr;
            set
            {
                if (_detail_Intr != value)
                {
                    _detail_Intr = value;
                    OnPropertyChanged();
                }
            }
        }

        private Music _openMusic;
        /// <summary>
        /// 打开封面时的歌
        /// </summary>
        public Music OpenMusic
        {
            get => _openMusic;
            set
            {
                if (_openMusic != value)
                {
                    _openMusic = value;
                    OnPropertyChanged();
                }
            }
        }

        private ObservableCollection<string> _openMusicName = new ObservableCollection<string>();
        /// <summary>
        /// 打开封面时的歌名
        /// </summary>
        public ObservableCollection<string> OpenMusicName
        {
            get => _openMusicName;
            set
            {
                if (_openMusicName != value)
                {
                    _openMusicName = value;
                    TitleWidth = 14 * value.Count + 57.93;
                    OnPropertyChanged();
                }
            }
        }

        private double _titleWidth = 0;
        /// <summary>
        /// 歌单页标题背景宽度
        /// </summary>
        public double TitleWidth
        {
            get => _titleWidth;
            set
            {
                if (_titleWidth != value)
                {
                    _titleWidth = value;
                    OnPropertyChanged();
                }
            }
        }

        private bool _vis_LoadingPage = true;
        /// <summary>
        /// 歌单加载页的显示/隐藏
        /// </summary>
        public bool Vis_LoadingPage
        {
            get => _vis_LoadingPage;
            set
            {
                if (_vis_LoadingPage != value)
                {
                    _vis_LoadingPage = value;
                    OnPropertyChanged();
                }
            }
        }
        #endregion 以上：/////////////////////非静态变量////////////////////////////


        #region //////////////////////////////静态方法//////////////////////////////

        #endregion 以上：/////////////////////静态方法//////////////////////////////


        #region //////////////////////////////非静态方法////////////////////////////

        /// <summary>
        /// 界面加载完成事件
        /// </summary>
        /// <param name="view">窗体/用户控件</param>
        private void ViewLoaded(object view)
        {
            MusicListView = view as MusicList;

            #region 加载图案旋转
            Image image = MusicListView.image_CD;

            //计算旋转中心
            Rect size = new Rect(image.RenderSize);
            double centerX = (size.TopLeft.X + size.TopRight.X + size.BottomLeft.X + size.BottomRight.X) / 4;
            double centerY = (size.TopLeft.Y + size.TopRight.Y + size.BottomLeft.Y + size.BottomRight.Y) / 4;

            image.RenderTransform = new RotateTransform(0, centerX, centerY);
            DoubleAnimation dbAscending = new DoubleAnimation(360, 0, new Duration(TimeSpan.FromSeconds(0.5)))
            { RepeatBehavior = RepeatBehavior.Forever, };
            Storyboard storyboard = new Storyboard();
            storyboard.Children.Add(dbAscending);
            Storyboard.SetTarget(dbAscending, image);
            Storyboard.SetTargetProperty(dbAscending, new PropertyPath("RenderTransform.Angle"));
            storyboard.Begin();
            #endregion 以上：黑胶图案旋转

            Vis_Vinyl.ValueChanged += Vis_Vinyl_ValueChanged;
            Vis_IntrDetailView.ValueChanged += Vis_IntrDetailView_ValueChanged;

            MusicListView.SizeChanged += MusicListView_SizeChanged;
            MusicListView.PreviewMouseDown += MusicListView_PreviewMouseDown;
            MusicListView.MouseDown += MusicListView_MouseDown;
            MusicListView.MouseDoubleClick += MusicListView_MouseDoubleClick;
            MusicListView.Closed += MusicListView_Closed;

            //加载用户设置
            FilePath.Instance.ConfigLoad();

            //读取歌曲列表
            Creator = Directory.Exists(FilePath.Instance.CreatorDir);
            if (_creator)
            { MusicListView.Width = 1280; }

            ReadMusicList();
            RefreshMusicListViewHeight();

            //设置默认的平台 ID
            PlatformID = 0;

            //判断是否开封面
            MethodInfo[] methodInfo = typeof(NewMusic).GetMethods();
            MethodInfo openMusic = methodInfo.FirstOrDefault(q => q.ReturnType.Name == "Music");
            if (openMusic != null)
            {
                string name = openMusic.Name;
                Music music = MusicList.FirstOrDefault(q => q.Title == name);
                if (music != null)
                {
                    OpenMusic = music;
                    ObservableCollection<string> nameChar = new ObservableCollection<string>();
                    foreach (char c in name)
                    { nameChar.Add(c.ToString()); }
                    OpenMusicName = nameChar;
                    Vis_Vinyl.StateMode = 1;
                }
            }

            //歌单加载页
            Task task = new Task(() => { Vis_LoadingPage = false; });
            task.Start();
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MusicListView_Closed(object sender, EventArgs e)
        {
            if (Vis_Vinyl.StateMode > 0)
            { Vis_Vinyl.StateMode = 0; }
        }

        /// <summary>
        /// 窗体尺寸变化事件
        /// </summary>
        /// <param name="sender">窗体</param>
        /// <param name="e"></param>
        private void MusicListView_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            int state = Convert.ToInt32(MusicListView.WindowState);
            if (state != _musicListViewState.StateMode)
            { MusicListViewState.StateMode = Convert.ToInt32(MusicListView.WindowState); }
        }

        /// <summary>
        /// 按钮按下 Command 方法
        /// </summary>
        /// <param name="sender">触发的按钮</param>
        private void BtnClick(object sender)
        {
            string tag = "";
            if (sender is Button btn)
            { tag = btn.Tag == null ? "" : btn.Tag.ToString(); }
            else if (sender is MenuItem item)
            { tag = item.Tag == null ? "" : item.Tag.ToString(); }

            switch (tag)
            {
                #region 窗体操作按钮
                case "MusicListViewClose":
                    { MusicListView.Close(); }
                    break;
                case "MusicListViewMinSize":
                    { MusicListView.WindowState = WindowState.Minimized; }
                    break;
                case "MusicListViewNormalSize":
                    { MusicListView.WindowState = WindowState.Normal; }
                    break;
                case "MusicListViewMaxSize":
                    { MusicListView.WindowState = WindowState.Maximized; }
                    break;
                #endregion 以上：窗体操作按钮

                case "Play":
                    { Play(_selectedMusic); }
                    break;
                case "ShowIntr_Music":
                    { ShowIntrDetail(InfoType.歌曲, _selectedMusic.Title, _selectedMusic.Introduction); }
                    break;
                case "ShowIntr_Singer":
                    {
                        if (IntroductionDic.Participants.ContainsKey(_selectedMusic.Singer))
                        { ShowIntrDetail(InfoType.参与者, _selectedMusic.Singer, IntroductionDic.Participants[_selectedMusic.Singer]); }
                        else
                        {
                            string infoStr = _selectedMusic.Singer == "佚名" ? "<" + _selectedMusic.Title + "/>无演唱者信息。" : "未找到<" + _selectedMusic.Singer + "/>信息。";
                            MessageBox.Show(infoStr, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    break;
                case "ShowIntr_Album":
                    {
                        if (IntroductionDic.Albums.ContainsKey(_selectedMusic.Album))
                        { ShowIntrDetail(InfoType.专辑, _selectedMusic.Album, IntroductionDic.Albums[_selectedMusic.Album]); }
                        else
                        {
                            string infoStr = (_selectedMusic.Album == "" || _selectedMusic.Album.ToLower() == "null") ? "<" + _selectedMusic.Title + "/>未收录于专辑。" : "未找到<" + _selectedMusic.Album + "/>信息。";
                            MessageBox.Show(infoStr, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    break;
                case "ShowLyric":
                    {
                        if (File.Exists(_selectedMusic.LyricPath))
                        {
                            Process process = new Process();
                            ProcessStartInfo psi = new ProcessStartInfo(_selectedMusic.LyricPath);
                            process.StartInfo = psi;
                            process.StartInfo.UseShellExecute = true;

                            try
                            { process.Start(); }
                            catch (Win32Exception ex)
                            { MessageBox.Show(ex.ToString(), "错误", MessageBoxButton.OK, MessageBoxImage.Error); }
                            catch (Exception ex)
                            { MessageBox.Show(ex.ToString(), "错误", MessageBoxButton.OK, MessageBoxImage.Error); }
                            finally
                            { process?.Close(); }
                        }
                        else
                        { MessageBox.Show("未找到<" + _selectedMusic.Title + "/>的歌词文件。", "错误", MessageBoxButton.OK, MessageBoxImage.Error); }
                    }
                    break;
                case "ShowIntr_Lyricist":
                    {
                        if (IntroductionDic.Participants.ContainsKey(_selectedMusic.Lyricist))
                        { ShowIntrDetail(InfoType.参与者, _selectedMusic.Lyricist, IntroductionDic.Participants[_selectedMusic.Lyricist]); }
                        else
                        {
                            string infoStr = _selectedMusic.Lyricist == "佚名" ? "<" + _selectedMusic.Title + "/>无作词者信息。" : "未找到<" + _selectedMusic.Lyricist + "/>信息。";
                            MessageBox.Show(infoStr, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    break;
                case "ShowScore":
                    {
                        if (File.Exists(_selectedMusic.ScorePath))
                        {
                            Process process = new Process();
                            ProcessStartInfo psi = new ProcessStartInfo(_selectedMusic.ScorePath);
                            process.StartInfo = psi;
                            process.StartInfo.UseShellExecute = true;

                            try
                            { process.Start(); }
                            catch (Win32Exception ex)
                            { MessageBox.Show(ex.ToString(), "错误", MessageBoxButton.OK, MessageBoxImage.Error); }
                            catch (Exception ex)
                            { MessageBox.Show(ex.ToString(), "错误", MessageBoxButton.OK, MessageBoxImage.Error); }
                            finally
                            { process?.Close(); }
                        }
                        else
                        { MessageBox.Show("未找到<" + _selectedMusic.Title + "/>的乐谱文件。", "错误", MessageBoxButton.OK, MessageBoxImage.Error); }
                    }
                    break;
                case "ShowIntr_Composer":
                    {
                        if (IntroductionDic.Participants.ContainsKey(_selectedMusic.Composer))
                        { ShowIntrDetail(InfoType.参与者, _selectedMusic.Composer, IntroductionDic.Participants[_selectedMusic.Composer]); }
                        else
                        {
                            string infoStr = _selectedMusic.Composer == "佚名" ? "<" + _selectedMusic.Title + "/>无作曲者信息。" : "未找到<" + _selectedMusic.Composer + "/>信息。";
                            MessageBox.Show(infoStr, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    break;
                case "OpenUrl":
                    {
                        if (_selectedMusic.CurrentUrl == "Local" || _selectedMusic.CurrentUrl.ToLower() == "null")
                        {
                            if (Creator)
                            { FilePath.Instance.OpenFolder(FilePath.Instance.CreatorDir); }
                            else
                            { FilePath.Instance.OpenFolder(FilePath.Instance.ResourceDir); }
                        }
                        else
                        { Process.Start(new ProcessStartInfo(_selectedMusic.CurrentUrl) { UseShellExecute = true }); }
                    }
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 键盘按下 Command 方法
        /// </summary>
        /// <param name="sender">触发的界面</param>
        private void KeyDown(object sender)
        {
            //Esc = 退出
            if (Keyboard.IsKeyDown(Key.Escape))
            {
                if (Vis_Vinyl.StateMode > 0)
                { Vis_Vinyl.StateMode = 0; }
            }

            //F1 = 查看代码行数
            if (Keyboard.IsKeyDown(Key.F1))
            {
                DirectoryInfo path = new DirectoryInfo(FilePath.Instance.Root);
                string slnFile = path.FullName;
                MessageBox.Show("已经码了 " + FilePath.Instance.LinesOfFolder(slnFile) + " 行代码了。", "辛苦了！", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        /// <summary>
        /// 窗体拖拽
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MusicListView_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            { MusicListView.DragMove(); }
        }

        /// <summary>
        /// 窗体双击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MusicListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                if (LatestClickedUI is null) { return; }

                //区分是主界面的什么控件触发的双击菜单
                object uIElm = GetMyTypeUI(LatestClickedUI, typeof(DockPanel));
                if (uIElm != null && uIElm is DockPanel dP && dP.Name == "dP_Title")
                {
                    if (MusicListView.WindowState == WindowState.Maximized)
                    { MusicListView.WindowState = WindowState.Normal; }
                    else if (MusicListView.WindowState == WindowState.Normal)
                    { MusicListView.WindowState = WindowState.Maximized; }
                }
            }
        }

        /// <summary>
        /// 歌单双击 = 播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MouseDoubleClick_List(object sender)
        {
            if (Mouse.LeftButton == MouseButtonState.Pressed)
            {
                if (sender is ThemedDataGrid dataGrid && dataGrid.SelectedItem != null && dataGrid.SelectedItem is Music music)
                { Play(music); }
            }
        }

        /// <summary>
        /// 播放，暂时只有动画
        /// </summary>
        /// <param name="music"></param>
        public void Play(Music music)
        {
            if (music is null)
            { return; }
            OpenMusic = music;

            ObservableCollection<string> nameChar = new ObservableCollection<string>();
            foreach (char c in music.Title)
            { nameChar.Add(c.ToString()); }
            OpenMusicName = nameChar;

            if (Vis_Vinyl.StateMode == 0)
            { Vis_Vinyl.StateMode = 1; }
            else
            {
                VinylViewModel.Instance.VinylView.Topmost = true;
                VinylViewModel.Instance.VinylView.Topmost = false;
            }
        }

        /// <summary>
        /// 展示介绍详情
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="title">标题</param>
        /// <param name="intr">介绍</param>
        public void ShowIntrDetail(InfoType type, string title, List<IntrLine> intr)
        {
            Detail_Type = type;
            Detail_Title = title;
            Detail_Intr = intr;

            if (Vis_IntrDetailView.StateMode == 0)
            { Vis_IntrDetailView.StateMode = 1; }
        }

        /// <summary>
        /// 主窗体的鼠标预按下的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void MusicListView_PreviewMouseDown(object sender, MouseEventArgs e)
        {
            if (e.OriginalSource is DependencyObject source && (e.OriginalSource is Visual || e.OriginalSource is Visual3D))
            { LatestClickedUI = source; }
        }

        /// <summary>
        /// 从 UI 树中找到指定类型的 UI 控件
        /// </summary>
        /// <param name="source"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public object GetMyTypeUI(DependencyObject source, Type type)
        {
            while (source.GetType().Name != type.Name)
            {
                try
                {
                    source = VisualTreeHelper.GetParent(source);
                    if (source is null || (!(source is Visual) && !(source is Visual3D)))
                    { return null; }
                }
                catch
                { return null; }
            }
            if (source is null)
            { return null; }
            else if (source.GetType().Name == type.Name)
            { return source; }
            else { return null; }
        }

        /// <summary>
        /// 读取歌单数据
        /// </summary>
        public void ReadMusicList()
        {
            List<Music> musicList = new List<Music>();
            string resourcePath = FilePath.Instance.ResourceDir;
            if (_creator)
            {
                resourcePath = FilePath.Instance.CreatorDir;
                foreach (string fileFullName in Directory.GetFileSystemEntries(FilePath.Instance.CreatorDir))
                {
                    if (fileFullName.Contains("歌单") && fileFullName.Contains(".xlsx"))
                    {
                        FilePath.Instance.MusicListPath = fileFullName;
                        List_Title = Path.GetFileNameWithoutExtension(fileFullName).Split('\\').Last();
                        break;
                    }
                }

                //如果是创作者进入，需要清空资源后从创作者资源里读取并备份
                FilePath.Instance.DeleteFolder(FilePath.Instance.InformationsDir);
                FilePath.Instance.DeleteFolder(FilePath.Instance.LyricsDir);
                FilePath.Instance.DeleteFolder(FilePath.Instance.ScoresDir);
            }
            else
            {
                foreach (string fileFullName in Directory.GetFileSystemEntries(FilePath.Instance.ResourceDir))
                {
                    if (fileFullName.Contains("歌单") && fileFullName.Contains(".xlsx"))
                    {
                        FilePath.Instance.MusicListPath = fileFullName;
                        List_Title = Path.GetFileNameWithoutExtension(fileFullName).Split('\\').Last();
                        break;
                    }
                }
            }

            try
            {
                //加载Excel工作簿并指名非商业应用
                ExcelPackage package = new ExcelPackage(FilePath.Instance.MusicListPath);
                ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
                ExcelWorksheet musicData = package.Workbook.Worksheets["Sheet1"];//读取工作簿中名为"Sheet1"的工作表

                //读取第一行内容，记录 Header 的列 ID
                Dictionary<string, int> columnID = new Dictionary<string, int>();
                for (int i = 1; i <= musicData.Columns.EndColumn; i++)
                {
                    object cellHeader = musicData.Cells[1, i].Value;
                    if (cellHeader != null && cellHeader.ToString() != "" && cellHeader.ToString().ToLower() != "null")
                    { columnID.Add(cellHeader.ToString(), i); }
                }

                int j = 1;
                string iDString = musicData.Cells[2, columnID["ID"]].Value?.ToString();
                while (!(iDString is null || iDString == ""))
                {
                    int iD = Convert.ToInt32(iDString);
                    string publishStr = "";
                    object cellValue = musicData.Cells[j + 1, columnID["公开"]].Value;
                    if (cellValue != null && cellValue.ToString() != "" && cellValue.ToString().ToLower() != "null")
                    { publishStr = cellValue.ToString(); }
                    bool publish = publishStr == "是";

                    //演唱者
                    string singer = "佚名";
                    cellValue = musicData.Cells[j + 1, columnID["演唱"]].Value;
                    if (cellValue != null && cellValue.ToString() != "" && cellValue.ToString().ToLower() != "null")
                    {
                        singer = cellValue.ToString();

                        //找到演唱者信息
                        foreach (string fileFullName in Directory.GetFileSystemEntries(resourcePath + @"\Informations"))
                        {
                            if (fileFullName.Contains("【参与者】" + singer + "_Info") && fileFullName.Contains(".txt"))
                            {
                                //记录到 IntroductionDic.Participants
                                if (!IntroductionDic.Participants.ContainsKey(singer))
                                {
                                    //解析Info
                                    string[] infos = File.ReadAllLines(fileFullName, Encoding.UTF8);
                                    IntroductionDic.Participants.Add(singer, new List<IntrLine>());

                                    foreach (string line in infos)
                                    {
                                        if (line.IndexOf(@"/// ") == 0)
                                        { IntroductionDic.Participants[singer].Add(new IntrLine(line)); }
                                    }
                                }

                                //公开歌曲的参与者介绍文件替换成最新版
                                string newPath = fileFullName.Replace(resourcePath, FilePath.Instance.ResourceDir);
                                if (_creator && publish && !File.Exists(newPath))
                                { FilePath.Instance.FileCopy(fileFullName, newPath); }
                                break;
                            }
                        }
                    }

                    Music music = new Music(singer, iD)
                    { Publish = publishStr, };

                    //非创作者歌单且不是发布的歌，就跳过
                    if (!_creator && !publish)
                    {
                        j++;
                        iDString = musicData.Cells[j + 1, columnID["ID"]].Value?.ToString();
                        continue;
                    }

                    //标题
                    cellValue = musicData.Cells[j + 1, columnID["标题"]].Value;
                    if (cellValue != null && cellValue.ToString() != "" && cellValue.ToString().ToLower() != "null")
                    { music.Title = cellValue.ToString(); }
                    string titleString = "【No." + music.ID + "】" + music.Title;

                    //名称
                    music.Name = singer + " - " + music.Title;

                    //作词
                    cellValue = musicData.Cells[j + 1, columnID["作词"]].Value;
                    if (cellValue != null && cellValue.ToString() != "" && cellValue.ToString().ToLower() != "null")
                    {
                        string lyricist = cellValue.ToString();
                        music.Lyricist = lyricist;

                        //找到作词者信息
                        foreach (string fileFullName in Directory.GetFileSystemEntries(resourcePath + @"\Informations"))
                        {
                            if (fileFullName.Contains("【参与者】" + lyricist + "_Info") && fileFullName.Contains(".txt"))
                            {
                                //记录到 IntroductionDic.Participants
                                if (!IntroductionDic.Participants.ContainsKey(lyricist))
                                {
                                    //解析Info
                                    string[] infos = File.ReadAllLines(fileFullName, Encoding.UTF8);
                                    IntroductionDic.Participants.Add(lyricist, new List<IntrLine>());

                                    foreach (string line in infos)
                                    {
                                        if (line.IndexOf(@"/// ") == 0)
                                        { IntroductionDic.Participants[lyricist].Add(new IntrLine(line)); }
                                    }
                                }

                                //公开歌曲的参与者介绍文件替换成最新版
                                string newPath = fileFullName.Replace(resourcePath, FilePath.Instance.ResourceDir);
                                if (_creator && publish && !File.Exists(newPath))
                                { FilePath.Instance.FileCopy(fileFullName, newPath); }
                                break;
                            }
                        }
                    }

                    //作曲
                    cellValue = musicData.Cells[j + 1, columnID["作曲"]].Value;
                    if (cellValue != null && cellValue.ToString() != "" && cellValue.ToString().ToLower() != "null")
                    {
                        string composer = cellValue.ToString();
                        music.Composer = composer;

                        //找到作曲者信息
                        foreach (string fileFullName in Directory.GetFileSystemEntries(resourcePath + @"\Informations"))
                        {
                            if (fileFullName.Contains("【参与者】" + composer + "_Info") && fileFullName.Contains(".txt"))
                            {
                                //记录到 IntroductionDic.Participants
                                if (!IntroductionDic.Participants.ContainsKey(composer))
                                {
                                    //解析Info
                                    string[] infos = File.ReadAllLines(fileFullName, Encoding.UTF8);
                                    IntroductionDic.Participants.Add(composer, new List<IntrLine>());

                                    foreach (string line in infos)
                                    {
                                        if (line.IndexOf(@"/// ") == 0)
                                        { IntroductionDic.Participants[composer].Add(new IntrLine(line)); }
                                    }
                                }

                                //公开歌曲的参与者介绍文件替换成最新版
                                string newPath = fileFullName.Replace(resourcePath, FilePath.Instance.ResourceDir);
                                if (_creator && publish && !File.Exists(newPath))
                                { FilePath.Instance.FileCopy(fileFullName, newPath); }
                                break;
                            }
                        }
                    }

                    //调
                    cellValue = musicData.Cells[j + 1, columnID["调"]].Value;
                    if (cellValue != null && cellValue.ToString() != "" && cellValue.ToString().ToLower() != "null")
                    { music.Key = cellValue.ToString(); }

                    //速度
                    cellValue = musicData.Cells[j + 1, columnID["速度"]].Value;
                    if (cellValue != null && cellValue.ToString() != "" && cellValue.ToString().ToLower() != "null")
                    { music.Speed = cellValue.ToString(); }

                    //拍号
                    cellValue = musicData.Cells[j + 1, columnID["拍号"]].Value;
                    if (cellValue != null && cellValue.ToString() != "" && cellValue.ToString().ToLower() != "null")
                    { music.Beat = cellValue.ToString(); }

                    //专辑
                    cellValue = musicData.Cells[j + 1, columnID["专辑"]].Value;
                    if (cellValue != null && cellValue.ToString() != "" && cellValue.ToString().ToLower() != "null")
                    {
                        string albumName = cellValue.ToString();
                        music.Album = albumName;

                        //找到专辑介绍
                        foreach (string fileFullName in Directory.GetFileSystemEntries(resourcePath + @"\Informations"))
                        {
                            if (fileFullName.Contains("【专辑】" + albumName + "_Info") && fileFullName.Contains(".txt"))
                            {
                                //记录到 IntroductionDic.Albums
                                if (!IntroductionDic.Albums.ContainsKey(albumName))
                                {
                                    //解析Info
                                    string[] infos = File.ReadAllLines(fileFullName, Encoding.UTF8);
                                    IntroductionDic.Albums.Add(albumName, new List<IntrLine>());

                                    foreach (string line in infos)
                                    {
                                        if (line.IndexOf(@"/// ") == 0)
                                        { IntroductionDic.Albums[albumName].Add(new IntrLine(line)); }
                                    }
                                }
                                music.Intr_Album = IntroductionDic.Albums[albumName];

                                //公开歌曲的专辑介绍文件替换成最新版
                                string newPath = fileFullName.Replace(resourcePath, FilePath.Instance.ResourceDir);
                                if (_creator && publish && !File.Exists(newPath))
                                { FilePath.Instance.FileCopy(fileFullName, newPath); }
                                break;
                            }
                        }
                    }

                    //专辑 Tag
                    cellValue = musicData.Cells[j + 1, columnID["#"]].Value;
                    if (cellValue != null && cellValue.ToString() != "" && cellValue.ToString().ToLower() != "null")
                    { music.AlbumTag = cellValue.ToString(); }

                    //Information文件查找
                    ExcelRange infoCell = musicData.Cells[j + 1, columnID["介绍"]];

                    if (infoCell.Hyperlink != null && File.Exists(resourcePath + @"\" + infoCell.Hyperlink))//原有链接存在并且有效，那就直接用
                    {
                        string fileFullName = resourcePath + @"\" + infoCell.Hyperlink;

                        //解析Info
                        string[] infos = File.ReadAllLines(fileFullName, Encoding.UTF8);
                        List<IntrLine> intrLines = new List<IntrLine>();
                        foreach (string line in infos)
                        {
                            if (line.IndexOf(@"/// ") == 0)
                            { intrLines.Add(new IntrLine(line)); }
                        }

                        if (intrLines.Count > 0)
                        { music.Introduction = intrLines; }

                        //公开歌曲的乐谱文件替换成最新版
                        if (_creator && publish)
                        { FilePath.Instance.FileCopy(fileFullName, fileFullName.Replace(resourcePath, FilePath.Instance.ResourceDir)); }
                    }
                    else
                    {
                        if (infoCell.Hyperlink != null)
                        { infoCell.Hyperlink = null; }

                        foreach (string fileFullName in Directory.GetFileSystemEntries(resourcePath + @"\Informations"))
                        {
                            if (fileFullName.Contains(titleString + "_Info") && fileFullName.Contains(".txt"))
                            {
                                //解析Info
                                string[] infos = File.ReadAllLines(fileFullName, Encoding.UTF8);
                                List<IntrLine> intrLines = new List<IntrLine>();
                                foreach (string line in infos)
                                {
                                    if (line.IndexOf(@"/// ") == 0)
                                    { intrLines.Add(new IntrLine(line)); }
                                }

                                if (intrLines.Count > 0)
                                { music.Introduction = intrLines; }

                                //生成超链接
                                string newName = fileFullName.Split('\\').Last();
                                string hyperLink = @"Informations\" + newName;
                                infoCell.SetHyperlink(new Uri(hyperLink, UriKind.Relative));

                                //公开歌曲的Information文件替换成最新版
                                if (_creator && publish)
                                {
                                    string newPath = fileFullName.Replace(resourcePath, FilePath.Instance.ResourceDir);
                                    FilePath.Instance.FileCopy(fileFullName, newPath);
                                }

                                break;
                            }
                        }
                    }

                    //Lyric文件查找
                    ExcelRange lyricCell = musicData.Cells[j + 1, columnID["歌词"]];

                    if (lyricCell.Hyperlink != null && File.Exists(resourcePath + @"\" + lyricCell.Hyperlink))//原有链接存在并且有效，那就直接用
                    {
                        string fileFullName = resourcePath + @"\" + lyricCell.Hyperlink;
                        music.LyricPath = fileFullName;

                        //公开歌曲的歌词文件替换成最新版
                        if (_creator && publish)
                        { FilePath.Instance.FileCopy(fileFullName, fileFullName.Replace(resourcePath, FilePath.Instance.ResourceDir)); }
                    }
                    else
                    {
                        if (lyricCell.Hyperlink != null)
                        { lyricCell.Hyperlink = null; }

                        foreach (string fileFullName in Directory.GetFileSystemEntries(resourcePath + @"\Lyrics"))
                        {
                            if (fileFullName.Contains(titleString + "_Lyric") && fileFullName.Contains(".pdf"))
                            {
                                music.LyricPath = fileFullName;

                                //生成超链接
                                string newName = fileFullName.Split('\\').Last();
                                string hyperLink = @"Lyrics\" + newName;
                                lyricCell.SetHyperlink(new Uri(hyperLink, UriKind.Relative));

                                //公开歌曲的歌词文件替换成最新版
                                if (_creator && publish)
                                {
                                    string newPath = fileFullName.Replace(resourcePath, FilePath.Instance.ResourceDir);
                                    FilePath.Instance.FileCopy(fileFullName, newPath);
                                }

                                break;
                            }
                        }
                    }

                    //Score文件查找
                    ExcelRange scoreCell = musicData.Cells[j + 1, columnID["乐谱"]];

                    if (scoreCell.Hyperlink != null && File.Exists(resourcePath + @"\" + scoreCell.Hyperlink))//原有链接存在并且有效，那就直接用
                    {
                        string fileFullName = resourcePath + @"\" + scoreCell.Hyperlink;
                        music.ScorePath = fileFullName;

                        //公开歌曲的乐谱文件替换成最新版
                        if (_creator && publish)
                        { FilePath.Instance.FileCopy(fileFullName, fileFullName.Replace(resourcePath, FilePath.Instance.ResourceDir)); }
                    }
                    else
                    {
                        if (scoreCell.Hyperlink != null)
                        { scoreCell.Hyperlink = null; }

                        foreach (string fileFullName in Directory.GetFileSystemEntries(resourcePath + @"\Scores"))
                        {
                            if (fileFullName.Contains(titleString + "_Score") && fileFullName.Contains(".pdf"))
                            {
                                music.ScorePath = fileFullName;

                                //生成超链接
                                string newName = fileFullName.Split('\\').Last();
                                string hyperLink = @"Scores\" + newName;
                                scoreCell.SetHyperlink(new Uri(hyperLink, UriKind.Relative));

                                //公开歌曲的乐谱文件替换成最新版
                                if (_creator && publish)
                                {
                                    string newPath = fileFullName.Replace(resourcePath, FilePath.Instance.ResourceDir);
                                    FilePath.Instance.FileCopy(fileFullName, newPath);
                                }

                                break;
                            }
                        }
                    }

                    //各种链接
                    foreach (ComboBoxItem item in MusicListView.cB_Platform.Items)
                    {
                        string platformName = item.Content.ToString();
                        if (platformName != "Local" && columnID.ContainsKey(platformName + "链接"))
                        {
                            cellValue = musicData.Cells[j + 1, columnID[platformName + "链接"]].Value;
                            if (cellValue != null && cellValue.ToString() != "" && cellValue.ToString().ToLower() != "null")
                            { music.Url_Dic.Add(platformName, cellValue.ToString()); }
                        }
                    }

                    //备注
                    cellValue = musicData.Cells[j + 1, columnID["备注"]].Value;
                    if (cellValue != null && cellValue.ToString() != "" && cellValue.ToString().ToLower() != "null")
                    { music.Notes = cellValue.ToString(); }
                    musicList.Add(music);

                    j++;
                    iDString = musicData.Cells[j + 1, columnID["ID"]].Value?.ToString();
                }

                if (_creator)
                {
                    //如果是创作者进入，保存歌单并备份到软件目录里
                    package.Save();
                    package.SaveAs(FilePath.Instance.ResourceDir + @"\" + _list_Title + ".xlsx");
                }

                //排序
                string rule = _creator ? "ID" : "Album";
                SortMusicList(musicList, rule);
            }
            catch
            { MessageBox.Show("请关闭歌单后重试！", "错误", MessageBoxButton.OK, MessageBoxImage.Error); }
        }

        /// <summary>
        /// 歌曲列表排序
        /// </summary>
        /// <param name="musicList">歌曲列表</param>
        /// <param name="rule">排序规则</param>
        public void SortMusicList(List<Music> musicList, string rule)
        {
            List<Music> oriList = musicList;
            List<Music> newList = new List<Music>();

            switch (rule)
            {
                case "Album":
                    {
                        //优先按专辑查找

                        Dictionary<string, int> albums = new Dictionary<string, int>();
                        foreach (Music music in oriList)
                        {
                            string albumName = music.Album;
                            if (IntroductionDic.Albums.ContainsKey(albumName))
                            {
                                if (albums.ContainsKey(albumName))
                                { albums[albumName]++; }
                                else
                                { albums.Add(albumName, 1); }
                            }
                        }

                        List<Music> publicSongs = new List<Music>();

                        for (int i = 0; i < albums.Count; i++)
                        {
                            string albumName = albums.ElementAt(i).Key;
                            List<Music> albumSongs = new List<Music>();
                            for (int j = oriList.Count; j > 0; j--)
                            {
                                Music music = oriList[j - 1];
                                if (music.Album == albumName)
                                {
                                    if (albumSongs.Count == 0)
                                    { albumSongs.Add(music); }
                                    else
                                    {
                                        int tag0 = Convert.ToInt32(music.AlbumTag);
                                        for (int k = 0; k < albumSongs.Count; k++)
                                        {
                                            int tag = Convert.ToInt32(albumSongs[k].AlbumTag);
                                            if (k == 0)
                                            {
                                                if (tag0 <= tag)
                                                {
                                                    albumSongs.Insert(0, music);
                                                    break;
                                                }
                                                else if (albumSongs.Count == 1)
                                                {
                                                    albumSongs.Add(music);
                                                    break;
                                                }
                                            }
                                            else if (k == albumSongs.Count - 1)
                                            {
                                                if (tag0 > tag)
                                                {
                                                    albumSongs.Add(music);
                                                    break;
                                                }
                                                else
                                                {
                                                    albumSongs.Insert(k, music);
                                                    break;
                                                }
                                            }
                                            else
                                            {
                                                if (tag0 > tag && tag0 <= Convert.ToInt32(albumSongs[k + 1].AlbumTag))
                                                {
                                                    albumSongs.Insert(k + 1, music);
                                                    break;
                                                }
                                            }
                                        }
                                    }

                                    oriList.Remove(music);
                                    if (albums[albumName] == 1)
                                    { albums.Remove(albumName); }
                                    else
                                    { albums[albumName]--; }
                                }
                            }
                            publicSongs.AddRange(albumSongs);
                        }

                        newList.AddRange(publicSongs);
                        newList.AddRange(oriList);

                        
                    }
                    break;
                case "ID":
                default:
                    { newList = oriList; }
                    break;
            }

            MusicList = new ObservableCollection<Music>(newList);
        }

        /// <summary>
        /// 黑胶界面显示变量的变更事件
        /// </summary>
        private void Vis_Vinyl_ValueChanged()
        {
            if (Vis_Vinyl.StateMode > 0)
            {
                Vinyl vinylView = new Vinyl();
                vinylView.Top = MusicListView.Top + MusicListView.Height + 50;
                vinylView.Left = MusicListView.Left + 50;
                vinylView.Show();
            }
            else
            { VinylViewModel.Instance.VinylView.Close(); }
        }

        /// <summary>
        /// 详情页显示变量的变更事件
        /// </summary>
        private void Vis_IntrDetailView_ValueChanged()
        {
            if (Vis_IntrDetailView.StateMode > 0)
            {
                IntrDetail introductionView = new IntrDetail();
                introductionView.ShowDialog();
            }
            else
            { IntrDetailViewModel.Instance.IntrDetailView.Close(); }
        }

        /// <summary>
        /// 刷新歌曲清单界面高度
        /// </summary>
        public void RefreshMusicListViewHeight()
        { MusicListView.Height = 23.77 * MusicList.Count + 80.83; }
        #endregion 以上：/////////////////////非静态方法////////////////////////////
    }
}
